package interpreter

import (
	"fmt"
	"parse/src/utils"
)

type List struct {
	*BaseData
	Elements []interface{}
}

func (l *List) ToString() string{
	result := ""
	for _,item := range l.Elements {
		result += fmt.Sprintf("%v",item) + "\n"
	}
	return result
}
// 实例化
func NewList(elements []interface{}) *List {
	temp := &List{BaseData: NewBaseData()}
	temp.InitList(elements)
	return temp
}

// 初始化list
func (l *List) InitList(elements []interface{}) {
	l.InitBaseData()
	l.Elements = elements
}

// 新增
func (l *List) AddedTo(other interface{}) (*List, interface{}) {
	newList := l.Copy()
	newList.Elements = append(newList.Elements, other)
	return newList, nil
}

// 相减
func (l *List) SubbedBy(other interface{}) (*List, interface{}) {
	if utils.IsInstance(other, "Number") {
		newList := l.Copy()
		other_ := other.(Number).Value.(int64)
		newList.Elements = append(newList.Elements[:other_], newList.Elements[other_+1:]...)
		return newList, nil
	}
	return nil, l.IllegalOperation(other)
}

// 相乘
func (l *List) MultedBy(other interface{}) (*List, interface{}) {
	if utils.IsInstance(other, "List") {
		newList := l.Copy()
		list := other.(List).Elements
		for key, value := range list {
			newList.Elements[key] = value
		}
		return newList, nil
	}
	return nil, l.IllegalOperation(other)
}

// 相除
func (l *List) DivedBy(other interface{}) (interface{}, interface{}) {
	if utils.IsInstance(other, "Number") {
		return l.Elements[other.(Number).Value.(int64)], nil
	}
	return nil, l.IllegalOperation(other)
}

// 拷贝
func (l *List) Copy() *List {
	copy_ := NewList(l.Elements)
	copy_.SetPos(l.PosStart, l.PosEnd)
	copy_.SetContext(l.Context)
	return copy_
}
